# -*- coding: utf-8 -*-
# @Time     : 2022/6/11 17:31
# @Author   : JustFly
# @File     : multiprocess_data_share.py
# @Software : PyCharm

import os
import random
import time
from multiprocessing import Process, Queue, Manager
"""
q = Queue 只适合子进程间通信
q = Manager().Queue() 适合父进程和子进程间通信
"""

# write process

def write(q):
    print(f'Process to write: {os.getpid()}')
    for value in ['A', 'B', 'C']:
        print(f'Put {value} to queue...')
        q.put(value)
        time.sleep(random.random())

# read process

def read(q):
    print(f'Process to read:{os.getpid()}')
    while True:
        value = q.get(True)
        print(f'Get {value} from queue.')


if __name__ == '__main__':
    # 父进程创建queue 并传递给各个子进程
    q = Queue()
    pw = Process(target=write, args=(q, ))
    pr = Process(target=read, args=(q, ))

    pw.start()
    pr.start()

    pw.join()

    # 强制结束读死循环
    pr.terminate()
